package com.jeomo.shiro.util;

import com.jeomo.shiro.dto.LoginInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.ThreadContext;

public class LoginSessionUtil {

    /**
     * 获取当前上下文状态信息
     *
     * @return
     * @Author qbt
     */
    public static LoginInfo getCurrentLoginInfo() {
        if (ThreadContext.getSecurityManager() == null) {
            return null;
        }
        Subject subject = SecurityUtils.getSubject();
        if (subject != null) {
            return (LoginInfo) (subject.getPrincipal());
        }
        return null;
    }

    /**
     * 切换登录信息，登录后，动态更改subject的登录属性
     *
     * @param currentOrgCode
     */
    public static LoginInfo setCurrentInfo(String currentOrgCode) {
        Subject subject = SecurityUtils.getSubject();
        LoginInfo loginInfo = (LoginInfo) (subject.getPrincipal());
        loginInfo.setCurrentOrgCode(currentOrgCode);
        PrincipalCollection principalCollection = subject.getPrincipals();
        String realmName = principalCollection.getRealmNames().iterator().next();
        PrincipalCollection newPrincipalCollection =
                new SimplePrincipalCollection(loginInfo, realmName);
        subject.runAs(newPrincipalCollection);
        return loginInfo;
    }

}
